package cn.com.dingtek.genius.manager.server.support.sam;

import cn.com.dingtek.genius.manager.server.support.sam.annotation.Logical;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

public interface Enforcer {
    boolean enforce(SamToken token, String[] policies, Logical logical);

    class BytePolicy {

        public static final char SEPARATOR = ',';

        //idx,pos均从0开始
        public static long[] grant(long[] sourse, int idx, int pos) {
            long[] result = copy(sourse, idx);
            result[idx] = result[idx] | (long) Math.pow(2, pos);
            return result;
        }

        public static long[] ungrant(long[] sourse, int idx, int pos) {
            long[] result = copy(sourse, idx);
            result[idx] = result[idx] & (~(long) Math.pow(2, pos));
            return result;
        }

        public static String key(int idx, int pos) {
            long[] result = grant(new long[]{0}, idx, pos);
            return StringUtils.join(result, SEPARATOR);
        }

        private static long[] copy(long[] sourse, int idx) {
            if (sourse.length < idx + 1) {
                return Arrays.copyOf(sourse, idx + 1);
            }
            return Arrays.copyOf(sourse, sourse.length);
        }

        public static boolean verify(long[] sourse, int idx, int pos) {
            if (sourse.length < idx + 1) {
                return false;
            }

            return (sourse[idx] & (long) Math.pow(2, pos)) != 0;
        }


        public static long[] convertPolicyEffect(String policyEffect) {
            String[] strs = StringUtils.split(policyEffect, ",");
            long[] result = new long[strs.length];

            for (int i = 0; i < strs.length; i++) {
                result[i] = Long.parseLong(strs[i]);
            }

            return result;
        }
    }
}
